<?php

namespace app\channel\controller\api;

use app\channel\ApiController;

use app\channel\model\ContractModel;
use think\Db;
use app\channel\model\OrderModel;
use app\channel\model\WalletModel;
use app\channel\model\AccountLogModel;
use app\channel\model\RechargeLogModel;
use app\channel\model\RewardLogModel;
use app\channel\model\RewardModel;
use app\channel\model\ProxyLevelModel;
use app\channel\model\ProxyUsersModel;
use app\mainadmin\model\PaymentModel;
use app\member\model\UsersModel;
use app\channel\model\ProxyUpapplyLogModel;

/*------------------------------------------------------ */
//-- 代理钱包相关
/*------------------------------------------------------ */

class Wallet extends ApiController
{
    /*------------------------------------------------------ */
    //-- 优先执行
    /*------------------------------------------------------ */
    public function initialize()
    {
        parent::initialize();
        $this->Model = new WalletModel();
    }
    /*------------------------------------------------------ */
    //-- 获取帐户信息
    /*------------------------------------------------------ */
    public function getWalletInfo()
    {
        $data['account'] = $this->Model->getWalletInfo($this->userInfo['user_id']);
        $income['day'] = $this->Model->countIncome($this->userInfo['user_id'], 'day');
        $income['month'] = $this->Model->countIncome($this->userInfo['user_id'], 'month');
        $income['day_pre'] = $income['month'] <= 0 ? 0 : priceFormat($income['day'] / $income['month'] * 100);
        $total_income = $data['account']['total_income'] + $data['account']['total_brokerage'];
        $income['month_pre'] = $income['month'] <= 0 ? 0 : priceFormat($income['month'] / $total_income * 100);
        $data['income'] = $income;
        $data['xdjj_total'] = (new RewardModel)->where('reward_type', 'xdjj')->value('ext_count');
        $this->success($data);
    }
    /*------------------------------------------------------ */
    //-- 获取余额信息
    /*------------------------------------------------------ */
    public function getBalanceInfo()
    {
        $data['account'] = $this->Model->getWalletInfo($this->userInfo['user_id']);
        $data['withdrawing'] = $this->Model->getWithdrawing($this->userInfo['user_id']);
        $this->success($data);
    }
    /*------------------------------------------------------ */
    //-- 获取收款信息
    /*------------------------------------------------------ */
    public function getPaymentList()
    {
        $paymentList = [];
        $userInfo = (new ProxyUsersModel)->info($this->userInfo['user_id'], false);
        if ($userInfo['byUser']['weixin_usd'] == 1) {
            $row['payment_code'] = 'wxpay';
            $row['payment_name'] = $this->Model->account_type['wxpay'];
            $row['payment_account'] = $userInfo['byUser']['weixin_account'];
            $paymentList[] = $row;
        }
        if ($userInfo['byUser']['alipay_usd'] == 1) {
            $row['payment_code'] = 'alipay';
            $row['payment_name'] = '支付宝';
            $row['payment_account'] = $userInfo['byUser']['alipay_account'];
            $paymentList[] = $row;
        }
        if ($userInfo['byUser']['bank_usd'] == 1) {
            $row['payment_code'] = 'bank';
            $row['payment_name'] = $userInfo['byUser']['bank_name'];
            $row['payment_account'] = $userInfo['byUser']['bank_card_number'];
            $paymentList[] = $row;
        }
        $data['paymentList'] = $paymentList;
        $this->success($data);
    }
    /*------------------------------------------------------ */
    //-- 获取余额日志列表
    /*------------------------------------------------------ */
    public function getBalanceLog()
    {
        $searchType = input('searchType', 'all', 'trim');
        $calendar = input('calendar', '', 'trim');
        if (empty($calendar)) {
            $startDate = date('Y-m-01', time());
            $startTime = strtotime($startDate);
            $endTime = strtotime("$startDate +1 month") - 1;
            $endDate = date('Y-m-d', $endTime);
        } else {
            $calendar = explode('~', $calendar);
            $startTime = strtotime($calendar[0]);
            $endTime = strtotime($calendar[1]) + 86399;
        }
        $where[] = ['user_id', '=', $this->userInfo['user_id']];
        $where[] = ['change_time', 'between', [$startTime, $endTime]];
        $AccountLogModel = new AccountLogModel();
        if ($searchType == 'income') {//收入
            $where[] = ['balance_money', '>', 0];
        } elseif ($searchType == 'outlay') {//支出
            $where[] = ['balance_money', '<', 0];
        } else {
            $where[] = ['balance_money', '<>', 0];
        }
        $data = $this->getPageList($AccountLogModel, $where, 'change_time,balance_money,change_desc', 6);
        foreach ($data['list'] as $key => $row) {
            $row['change_time'] = dateTpl($row['change_time'], 'Y-m-d H:i:s', true);
            $data['list'][$key] = $row;
        }
        if (empty($calendar)) {
            $data['startDate'] = $startDate;
            $data['endDate'] = $endDate;
        }
        $p = input('p', '1', 'intval');
        if ($searchType == 'all' && $p == 1) {//全部，并且为第一页时统计收入和支出
            $_where = $where;
            $_where[] = ['balance_money', '>', 0];
            $data['income'] = $AccountLogModel->where($_where)->SUM('balance_money');
            $_where = $where;
            $_where[] = ['balance_money', '<', 0];
            $data['outlay'] = $AccountLogModel->where($_where)->SUM('balance_money');
            $data['outlay'] = $data['outlay'] * -1;
        }
        return $this->success($data);
    }
    /*------------------------------------------------------ */
    //-- 获取货款收支统计列表
    /*------------------------------------------------------ */
    public function getGoodsMoneyStatic()
    {
        $data['goods_money'] = $this->userInfo['account']['goods_money'];
        $data['goods_money_total'] = $this->userInfo['account']['goods_money'] + $this->userInfo['account']['goods_money_outlay_total'];
        $data['goods_money_outlay_total'] = $this->userInfo['account']['goods_money_outlay_total'];
        $data['goods_money_total_pre'] = priceFormat($data['goods_money_outlay_total'] / $data['goods_money_total'] * 100) * 1;
        return $this->success($data);
    }
    /*------------------------------------------------------ */
    //-- 获取货款日志列表
    /*------------------------------------------------------ */
    public function getGoodsMoneyLog()
    {
        $state = input('state', 'all', 'trim');
        $where[] = ['user_id', '=', $this->userInfo['user_id']];
        if ($state == 'inc') {//充值
            $where[] = ['goods_money', '>', 0];
        } elseif ($state == 'dec') {//支出
            $where[] = ['goods_money', '<', 0];
        } else {
            $where[] = ['goods_money', '<>', 0];
        }
        $AccountLogModel = new AccountLogModel();
        $data = $this->getPageList($AccountLogModel, $where, '', 10);
        foreach ($data['list'] as $key => $row) {
            $row['change_time'] = dateTpl($row['change_time'], 'Y-m-d H:i:s', true);
            $data['list'][$key] = $row;
        }
        return $this->success($data);
    }
    /*------------------------------------------------------ */
    //-- 获取升级货款收支统计列表
    /*------------------------------------------------------ */
    public function getUplevelGoodsMoneyStatic()
    {
        $data['money'] = $this->userInfo['account']['uplevel_goods_money'];
        $data['money_total'] = $this->userInfo['account']['uplevel_goods_money_total'];
        $data['money_outlay_total'] = $this->userInfo['account']['uplevel_goods_money_total'] - $this->userInfo['account']['uplevel_goods_money'];
        $data['money_total_pre'] = priceFormat($data['money_outlay_total'] / $data['money_total'] * 100) * 1;
        return $this->success($data);
    }
    /*------------------------------------------------------ */
    //-- 获取升级货款日志列表
    /*------------------------------------------------------ */
    public function getUplevelGoodsMoneyLog()
    {
        $state = input('state', 'all', 'trim');
        $where[] = ['user_id', '=', $this->userInfo['user_id']];
        if ($state == 'inc') {//充值
            $where[] = ['uplevel_goods_money', '>', 0];
        } elseif ($state == 'dec') {//支出
            $where[] = ['uplevel_goods_money', '<', 0];
        } else {
            $where[] = ['uplevel_goods_money', '<>', 0];
        }
        $AccountLogModel = new AccountLogModel();
        $data = $this->getPageList($AccountLogModel, $where, '', 10);
        foreach ($data['list'] as $key => $row) {
            $row['change_time'] = dateTpl($row['change_time'], 'Y-m-d H:i:s', true);
            $data['list'][$key] = $row;
        }
        return $this->success($data);
    }
    /*------------------------------------------------------ */
    //-- 获取保证金收支统计列表
    /*------------------------------------------------------ */
    public function getEarnestMoneyStatic()
    {
        $data['earnest_money'] = $this->userInfo['account']['earnest_money'];
        $data['earnest_money_outlay_total'] = $this->userInfo['account']['earnest_money_outlay_total'];
        $data['earnest_money_total'] = $data['earnest_money'] + $data['earnest_money_outlay_total'];
        $data['earnest_money_total_pre'] = priceFormat($data['earnest_money_outlay_total'] / $data['earnest_money_total'] * 100) * 1;
        return $this->success($data);
    }
    /*------------------------------------------------------ */
    //-- 获取保证金日志列表
    /*------------------------------------------------------ */
    public function getEarnestMoneyLog()
    {
        $state = input('state', 'all', 'trim');
        $where[] = ['user_id', '=', $this->userInfo['user_id']];
        if ($state == 'inc') {//充值
            $where[] = ['earnest_money', '>', 0];
        } elseif ($state == 'dec') {//支出
            $where[] = ['earnest_money', '<', 0];
        } else {
            $where[] = ['earnest_money', '<>', 0];
        }
        $AccountLogModel = new AccountLogModel();
        $data = $this->getPageList($AccountLogModel, $where, '', 10);
        foreach ($data['list'] as $key => $row) {
            $row['change_time'] = dateTpl($row['change_time'], 'Y-m-d H:i:s', true);
            $data['list'][$key] = $row;
        }
        return $this->success($data);
    }
    /*------------------------------------------------------ */
    //-- 充值日志列表
    /*------------------------------------------------------ */
    public function getRechargeLog()
    {
        $type = input('type', '', 'trim');
        $RechargeLogModel = new RechargeLogModel();
        $where[] = ['user_id', '=', $this->userInfo['user_id']];
        $where[] = ['type', '=', $type];
        $where[] = ['pay_time', '>', 0];
        $data = $this->getPageList($RechargeLogModel, $where, '', 10);
        foreach ($data['list'] as $key => $row) {
            $row['add_time'] = dateTpl($row['add_time'], 'Y-m-d H:i:s', true);
            $data['list'][$key] = $row;
        }
        return $this->success($data);
    }
    /*------------------------------------------------------ */
    //-- 充值支付调用
    /*------------------------------------------------------ */
    public function getRechargePayInfo()
    {
        $settings = settings();
        $platform = input('platform', '', 'trim');
        $payList = (new PaymentModel)->getRows($platform);
        $channel_recharge_payment = explode(',', $settings['channel_recharge_payment']);
        $channel_receive_payment_set = $settings['channel_receive_payment_set'];
        $data['payList'] = [];
        $isOffLinePay = 0;
        $user = (new ProxyUsersModel())->info($this->userInfo['user_id']);
        foreach ($payList as $pay) {
//            if (in_array($pay['pay_code'], $channel_recharge_payment) == false) {
//                continue;
//            }
//            if ($user['supply_uid'] > 0 && $pay['pay_code'] != 'offline') {
//                continue;
//            }
//            if ($pay['pay_code'] == 'offline') {
//                $isOffLinePay = 1;
//            }
            if ($channel_receive_payment_set == 1 && $pay['pay_code'] != 'offline') {
                continue;
            }
            $_pay['pay_id'] = $pay['pay_id'];
            $_pay['pay_code'] = $pay['pay_code'];
            $_pay['pay_name'] = $pay['pay_name'];
            $data['payList'][] = $_pay;
        }
        $proxy_id = input('proxy_id', 0, 'trim');
        $ProxyLevelList = (new ProxyLevelModel)->getList();
        $supply_uid = (new ProxyUsersModel())->getSupplyUid($this->userInfo['user_id'], $proxy_id, $ProxyLevelList);
        if ($supply_uid > 0) { // 打款给代理
            $userInfo = (new ProxyUsersModel)->info($supply_uid);
            $byUser = $userInfo['byUser'];
            $data['offline']['is_usd'] = 0;
            $data['offline']['weixin_usd'] = $byUser['weixin_usd'];
            if ($byUser['weixin_usd'] == 1) {
                $data['offline']['is_usd'] = 1;
                $data['offline']['weixin_qrcode'] = $byUser['weixin_qrcode'];
                $data['offline']['weixin_name'] = $byUser['weixin_name'];
                $data['offline']['weixin_account'] = $byUser['weixin_account'];
            }
            $data['offline']['alipay_usd'] = $byUser['alipay_usd'];
            if ($byUser['alipay_usd'] == 1) {
                $data['offline']['is_usd'] = 1;
                $data['offline']['alipay_qrcode'] = $byUser['alipay_qrcode'];
                $data['offline']['alipay_name'] = $byUser['alipay_name'];
                $data['offline']['alipay_account'] = $byUser['alipay_account'];
            }
            $data['offline']['bank_usd'] = $byUser['bank_usd'];
            if ($byUser['bank_usd'] == 1) {
                $data['offline']['is_usd'] = 1;
                $data['offline']['bank_name'] = $byUser['bank_name'];
                $data['offline']['bank_subbranch'] = $byUser['bank_subbranch'];
                $data['offline']['bank_card_number'] = $byUser['bank_card_number'];
                $data['offline']['bank_user_name'] = $byUser['bank_user_name'];
            }
        } else { // 打款给平台
            //if ($isOffLinePay == 1) {
            $data['offline']['weixin_usd'] = $settings['channel_weixin_usd'] * 1;
            $data['offline']['alipay_usd'] = $settings['channel_alipay_usd'] * 1;
            $data['offline']['bank_usd'] = $settings['channel_bank_usd'] * 1;
            if ($data['offline']['weixin_usd'] == 1) {
                $data['offline']['is_usd'] = 1;
                $data['offline']['weixin_qrcode'] = $settings['channel_weixin_qrcode'];
                $data['offline']['weixin_name'] = $settings['channel_weixin_name'];
                $data['offline']['weixin_account'] = $settings['channel_weixin_account'];
            }
            if ($data['offline']['alipay_usd'] == 1) {
                $data['offline']['is_usd'] = 1;
                $data['offline']['alipay_qrcode'] = $settings['channel_alipay_qrcode'];
                $data['offline']['alipay_name'] = $settings['channel_alipay_name'];
                $data['offline']['alipay_account'] = $settings['channel_alipay_account'];
            }
            if ($data['offline']['bank_usd'] == 1) {
                $data['offline']['bank_name'] = $settings['channel_bank_name'];
                $data['offline']['bank_subbranch'] = $settings['channel_bank_subbranch'];
                $data['offline']['bank_user_name'] = $settings['channel_bank_user_name'];
                $data['offline']['bank_card_number'] = $settings['channel_bank_card_number'];
            }
            //}
        }
        return $this->success($data);
    }
    /*------------------------------------------------------ */
    //-- 充值提交
    /*------------------------------------------------------ */
    public function postRecharge()
    {
        $money = input('money') * 1;
        if ($money <= 0) {
            return $this->error('请输入充值金额.');
        }
        $remark = input('remark', '', 'trim');
        $type = input('type', '', 'trim');
        $payCode = input('payCode', '', 'trim');
        $fileList = input('fileList', '', 'trim');
        $proxy_id = input('proxy_id', '', 'trim');
        $upgrade_type = input('upgrade_type', 0, 'trim');
        $order_type = input('order_type', 0, 'trim');
        //if ($type == 'earnestMoney') {
        //    $account = (new WalletModel)->where('user_id', $this->userInfo['user_id'])->find();
        //    $earnest_money = $account['earnest_money_total'] + $money;
        //    $order_aoumt = (new OrderModel())->getAllAmount($this->userInfo['user_id']);
        //    $proxy_id = (new ProxyLevelModel())->where('earnest_money', '<=', $earnest_money)
        //        ->where('replenish_money', '<=', $order_aoumt)->order('level', 'asc')->value('proxy_id');
        //}
        if ($payCode == 'offline' && empty($fileList)) {
            return $this->error('请上传付款凭证.');
        }
        $payList = (new PaymentModel)->getRows(false, 'pay_code');
        if (empty($payList[$payCode])) {
            return $this->error('支付方式错误，请重试.');
        }

        $contract = (new ContractModel())->getContractByUserIdAndProxyId($this->userInfo['user_id'], $proxy_id);
        if (empty($contract) || $contract['is_signature'] != 1) {
            return $this->error('请先签约合同.');
        }

        $order_id = $this->Model->saveRecharge($money, $type, $remark, $payList[$payCode], $payCode, $fileList, $proxy_id, $upgrade_type, $order_type);
        if (is_numeric($order_id) == false) {
            return $this->error($order_id);
        }
        $data['order_id'] = $order_id;
        return $this->success($data);
    }
    /*------------------------------------------------------ */
    //-- 获取奖励日志列表
    /*------------------------------------------------------ */
    public function getRewardLog()
    {
        $state = input('state', 'all', 'trim');
        $rewardType = input('rewardType', 'all', 'trim');
        $calendar = input('calendar', '', 'trim');
        $reward_type = input('reward_type', '', 'trim');
        $types = input('type', 0, 'intval');
        if (empty($calendar)) {
            //获取当前用户参与的奖项
            $rewardList = (new RewardModel)->getJoinReward($this->userInfo['proxy_id'], $this->userInfo['region_proxy']);
            $startDate = date('Y-m-01', time());
            $startTime = strtotime($startDate);
            $endTime = strtotime("$startDate +1 month") - 1;
            $endDate = date('Y-m-d', $endTime);
        } else {
            $calendar = explode('~', $calendar);
            $startTime = strtotime($calendar[0]);
            $endTime = strtotime($calendar[1]) + 86399;
        }
        if ($rewardType != 'all') {
//            $where[] = ['reward_type', '=', $rewardType];
            $where[] = "reward_type =  'tzsjjl'";
        }
//        $where[] = " add_time between {$startTime} AND {$endTime} ";
        if ($state == '1') {//待返
            $where[] = ' (status <= 1 OR status = 3) ';
        } elseif ($state == '2') {//已返
            $where[] = ' status = 2';
        } elseif ($state == '9') {//已取消
            $where[] = ' status = 9';
        }
        $where[] = " (reward_type != 'dtgbh' AND reward_type != 'tzsjjl')";
        /*$where[] = ['to_uid', '=', $this->userInfo['user_id']];
        if ($rewardType != 'all') {
            $where[] = ['reward_type', '=', $rewardType];
        }
        $where[] = ['add_time', 'between', [$startTime, $endTime]];
        if ($state == '1') {//待返
            $where[] = ['status', '<=', 1];
        } elseif ($state == '2') {//已返
            $where[] = ['status', '=', 2];
        } elseif ($state == '9') {//已取消
            $where[] = ['status', '=', 9];
        }*/
//        var_dump($where);die;
        $user_id = $this->userInfo['user_id'];
        $where[] = "(to_uid = {$user_id} OR payer_uid = {$user_id}) ";
//        var_dump($user_id);
//        var_dump($where);
//        die;
        $RewardLogModel = new RewardLogModel();
        $viewObj = $RewardLogModel->where(join(' AND ', $where))
            ->order('add_time desc');

        $data = $this->getPageList($RewardLogModel, $viewObj, '', 10);
        $ProxyLevelModel = new ProxyLevelModel();

        $UsersModel = new UsersModel();
        $proxyLevel = $ProxyLevelModel->getList();
        foreach ($data['list'] as $key => $row) {
            switch ($row['margin_audit_status']) {
                case 0:
                    $msg = "待打款";
                    break;
                case 1:
                    $msg = "待确认";
                    break;
                case 2:
                    $msg = "已返";
                    break;
                case 3:
                    $msg = "确认失败";
                    break;
                case 4:
                    $msg = "审核失败";
                    break;
                default:
                    $msg = "";
            }

            $row['statusd'] = $msg;
//            var_dump($row);die;
            $row['add_time'] = dateTpl($row['add_time'], 'Y-m-d H:i:s', true);
            $row['to_proxy_name'] = $proxyLevel[$row['to_proxy_id']]['proxy_name'];
            if ($row['reward_type'] == "tzsjjl") {
                $channel_proxy_users_recharge_log = Db::name('channel_proxy_users_recharge_log')->where(array('order_id' => $row['from_id'], 'upgrade_type' => 2))->field('order_amount')->find();
                if ($channel_proxy_users_recharge_log) {
                    $row['bond_recharge_amount'] = $channel_proxy_users_recharge_log['order_amount'];
                } else {
                    $row['bond_recharge_amount'] = 0;
                }
            } else {
                $row['bond_recharge_amount'] = 0;
            }

            $row['buttom'] = 0;
            $row['userinfo'] = $UsersModel->info($row['from_uid']);
            if ($row['to_uid'] == $user_id) { // 奖励
                if ($row['status'] == 3) {
                    $row['buttom'] = 1;
                }
            } else { // 发奖
                if ($row['status'] == 1) {
                    $row['buttom'] = 2;
                }
            }
            if ($types == 0) {
                $row['status'] = $RewardLogModel->status[$row['status']];

            }
            $data['list'][$key] = $row;
        }
        if (empty($calendar)) {
            $data['rewardList'] = $rewardList;
            $data['startDate'] = $startDate;
            $data['endDate'] = $endDate;
        }
        return $this->success($data);
    }
    /*------------------------------------------------------ */
    //-- 保证金奖励列表
    /*------------------------------------------------------ */
    public function getBondLog()
    {
        $state = input('state', 'all', 'trim');
        $rewardType = input('rewardType', 'all', 'trim');
        $calendar = input('calendar', '', 'trim');
        $reward_type = input('reward_type', '', 'trim');
        $types = input('type', 0, 'intval');

        $where[] = "reward_type =  'tzsjjl'";
        $where[] = "surrender_order_status =  1";


        if ($state != 'all' && $state != 99) {//待返
            $where[] = ' margin_audit_status ='.$state;
        }
        $user_id = $this->userInfo['user_id'];
        if ($types==2) {
            $where[] = " supply_uid = {$user_id} ";
        }elseif ($types==1){
            $where[] = " to_uid = {$user_id} ";
        }
        $RewardLogModel = new RewardLogModel();
        $viewObj = $RewardLogModel->where(join(' AND ', $where))
            ->order('add_time desc');

        $data = $this->getPageList($RewardLogModel, $viewObj, '', 10);
        $ProxyLevelModel = new ProxyLevelModel();

        $UsersModel = new UsersModel();
        $proxyLevel = $ProxyLevelModel->getList();
        foreach ($data['list'] as $key => $row) {

            //获取发奖励人
            $mobile=Db::name('users')->where(array('user_id'=>$row['supply_uid']))->field('mobile')->find()['mobile'];
            $row['jl_user_mobile']=$mobile;
            //获奖用户
            $h_mobile=Db::name('users')->where(array('user_id'=>$row['to_uid']))->field('mobile')->find()['mobile'];
            $row['hj_user_mobile']=$h_mobile;
            switch ($row['margin_audit_status']) {
                case 0:
                    $msg = "待打款";
                    break;
                case 1:
                    $msg = "待确认";
                    break;
                case 2:
                    $msg = "已返";
                    break;
                case 3:
                    $msg = "确认失败";
                    break;
                case 4:
                    $msg = "审核失败";
                    break;
                default:
                    $msg = "";
            }

            $row['statusd'] = $msg;
//            var_dump($row);die;
            $row['add_time'] = dateTpl($row['add_time'], 'Y-m-d H:i:s', true);
            $row['to_proxy_name'] = $proxyLevel[$row['to_proxy_id']]['proxy_name'];
            if ($row['reward_type'] == "tzsjjl") {
                $channel_proxy_users_recharge_log = Db::name('channel_proxy_users_recharge_log')->where(array('order_id' => $row['from_id'], 'upgrade_type' => 2))->field('order_amount')->find();
                if ($channel_proxy_users_recharge_log) {
                    $row['bond_recharge_amount'] = $channel_proxy_users_recharge_log['order_amount'];
                } else {
                    $row['bond_recharge_amount'] = 0;
                }
            } else {
                $row['bond_recharge_amount'] = 0;
            }

            $row['buttom'] = 0;
            $row['userinfo'] = $UsersModel->info($row['from_uid']);
            if ($row['to_uid'] == $user_id) { // 奖励
                if ($row['status'] == 3) {
                    $row['buttom'] = 1;
                }
            } else { // 发奖
                if ($row['status'] == 1) {
                    $row['buttom'] = 2;
                }
            }
            if ($types == 0) {
                $row['status'] = $RewardLogModel->status[$row['status']];

            }
            $data['list'][$key] = $row;
        }
        if (empty($calendar)) {
            $data['rewardList'] = $rewardList;
            $data['startDate'] = $startDate;
            $data['endDate'] = $endDate;
        }
        return $this->success($data);
    }

    /*------------------------------------------------------ */
    //-- 获取下级充值列表
    /*------------------------------------------------------ */
    public function getJuniorRechargeLog()
    {
        $user_id = $this->userInfo['user_id'];
        $where[] = ['supply_uid', '=', $user_id];
        $state = input('state', 0, 'intval');
        switch ($state) {
            case 1:
                $where[] = ['status', '=', 0];
                break;
            case 2:
                $where[] = ['status', '=', 9];
                break;
            case 3:
                $where[] = ['status', '=', 1];
                break;
            default:
                break;
        }
        $where[] = ['order_type', '=', 1];
        $RechargeLogModel = new RechargeLogModel();
        $data = $this->getPageList($RechargeLogModel, $where, '', 10);
        $status_list = $RechargeLogModel->status;
        $UsersModel = new UsersModel();
        foreach ($data['list'] as $key => $val) {
            $data['list'][$key]['add_time'] = dateTpl($val['add_time'], 'Y-m-d H:i:s', true);
            $data['list'][$key]['ostatus'] = $status_list[$val['status']];
            $data['list'][$key]['junior'] = $UsersModel->info($val['user_id']);
        }
        return $this->success($data);
    }

    public function getJuniorRechargeLogInfo()
    {
        $order_id = input('order_id', '', 'trim');
        $RechargeLogModel = new RechargeLogModel();
        $data['order'] = $RechargeLogModel->getInfo(['order_id' => $order_id]);
        if (empty($data['order'])) {
            $this->error('记录不存在');
        }
        $data['junior'] = (new ProxyUsersModel())->info($data['order']['user_id']);
        return $this->success($data);
    }
    /*------------------------------------------------------ */
    //-- 确认保证金收款
    /*------------------------------------------------------ */
    public function checkPay()
    {
        $order_id = input('order_id', '', 'trim');
        $RechargeModel = new RechargeLogModel();
        // 订单信息
        $info = $RechargeModel->where('order_id', $order_id)->find();
        if ($info['supply_uid'] != $this->userInfo['user_id']) {
            return $this->error('无权限审核');
        }
        $status = input('status', 0, 'intval');
        $check_remark = input('check_remark', '', 'trim');

        Db::startTrans();//开启事务
        if ($status == 9) {
            if ($info['pay_code'] != 'offline') {
                Db::rollback();//回滚事务
                return $this->error('非法操作，只有线下支付的才能操作审批.');
            }
            $res = $RechargeModel->updatePay($order_id, $check_remark);
            if ($res !== true) {
                Db::rollback();//回滚事务
                return $this->error($res);
            }
            $ProxyUsersModel = new ProxyUsersModel();
            // 用户信息
            $userinfo = $ProxyUsersModel->where('user_id', $info['user_id'])->find();
            $ProxyUpapplyLogModel = new ProxyUpapplyLogModel();
            $where[] = ['user_id', '=', $info['user_id']];
            $where[] = ['status', '=', 0];
            $count = $ProxyUpapplyLogModel->where($where)->count();
            if ($count > 0) {
                Db::rollback();//回滚事务
                return $this->error('您已提交升级申请，正在审核中，不能重复提交.');
            }
            $ProxyLevelModel = new ProxyLevelModel();

            $levelList = $ProxyLevelModel->getList();
            $rows = array_reverse($levelList);//反转数组
            unset($rows[0]);
            $proxy_id = 0;
            $ProxyUsersModel = new ProxyUsersModel();
            $userinfo = $ProxyUsersModel->where('user_id', $info['user_id'])->find();
            foreach ($rows as $key => $row) {
                if ($row['proxy_id'] < $userinfo['proxy_id']) {
                    $proxy_id = $row['proxy_id'];
                    break;
                }
            }

            $inData['user_id'] = $userinfo['user_id'];
            $inData['proxy_id'] = $userinfo['proxy_id'];
            $inData['up_proxy_id'] = $proxy_id;
            $inData['pid'] = $userinfo['pid'];
            $inData['bond_voucher'] = $info['imgs'];
            if ($inData['pid'] > 0) {
                $pUserInfo = $ProxyUsersModel->info($inData['pid']);
                $inData['pid_proxy_id'] = $pUserInfo['proxy_id'];
            }
            $inData['supply_uid'] = $userinfo['supply_uid'];
            if ($inData['supply_uid'] > 0) {
                $sUserInfo = $ProxyUsersModel->info($inData['pid']);
                $inData['supply_proxy_id'] = $sUserInfo['proxy_id'];
            }
            // 订单类型
            if ($info['upgrade_type'] == 2) {
                $inData['type'] = 2;
            } else {
                $inData['type'] = 1;
            }
            $inData['order_id'] = $order_id;
            $inData['add_time'] = time();
            // 添加审核记录
            $res = $ProxyUpapplyLogModel->save($inData);
            if ($res < 1) {
                Db::rollback();//回滚事务
                return $this->error('录入升级申请失败，请重试.');
            }
        } else {
            if (empty($check_remark)) {
                Db::rollback();//回滚事务
                return $this->error('请填写拒绝理由.');
            }
            $upData['status'] = 1;
            $upData['check_remark'] = $check_remark;
            $upData['admin_id'] = AUID;
            $upData['check_time'] = time();
            $res = $RechargeModel->where('order_id', $order_id)->update($upData);
            if ($res < 1) {
                Db::rollback();//回滚事务
                return $this->error('操作失败，请重试.');
            }
        }


        Db::commit();//提交事务
        return $this->success('操作成功.', 'reload');
    }

    /*------------------------------------------------------ */
    //-- 确认保证金收款
    /*------------------------------------------------------ */
//    public function checkPay()
//    {
//        $order_id = input('order_id', '', 'trim');
//        $RechargeModel = new RechargeLogModel();
//        $info = $RechargeModel->where('order_id', $order_id)->find();
//        if ($info['supply_uid'] != $this->userInfo['user_id']) {
//            return $this->error('无权限审核');
//        }
//        $status = input('status', 0, 'intval');
//        $check_remark = input('check_remark', '', 'trim');
//        if ($status == 9) {
//            if ($info['pay_code'] != 'offline') {
//                return $this->error('非法操作，只有线下支付的才能操作审批.');
//            }
//            $res = $RechargeModel->updatePay($order_id, $check_remark);
//            if ($res !== true) {
//                return $this->error($res);
//            }
//        } else {
//            $upData['status'] = 1;
//            $upData['check_remark'] = $check_remark;
//            $upData['admin_id'] = AUID;
//            $upData['check_time'] = time();
//            $res = $RechargeModel->where('order_id', $order_id)->update($upData);
//            if ($res < 1) {
//                return $this->error('操作失败，请重试.');
//            }
//        }
//        return $this->success('操作成功.', 'reload');
//    }

    /*------------------------------------------------------ */
    //-- 佣金记录处理
    /*------------------------------------------------------ */
    public function disposeRewardLog()
    {
        $id = input('id', '', 'trim');
        $status = input('status', 0, 'intval');
        $remark = input('remark', '', 'trim');
        $RewardLog = new RewardLogModel();
        $info = $RewardLog->where('id', $id)->find();
        $user_id = $this->userInfo['user_id'];
        if (empty($info)) return $this->error('无该记录');
        Db::startTrans();//开启事务
        switch ($status) {
            case 3: // 上级打款
                if ($info['payer_uid'] != $user_id) {
                    Db::rollback(); // 回滚事务
                    return $this->error('无权操作');
                }
                break;
            case 2: // 下级收款
                if ($info['to_uid'] != $user_id) {
                    Db::rollback(); // 回滚事务
                    return $this->error('无权操作');
                }
                $userinfo = $this->Model->where(['user_id' => $user_id])->find();
                if (!$this->Model->where(['user_id' => $user_id])->update(['earnest_money' => $userinfo['earnest_money'] + $info['reward_money']])) {
                    Db::rollback();
                    return $this->error('操作失败');
                } else {
                    $AccountLogModel = new AccountLogModel();
                    $save_data = [
                        'user_id' => $user_id, 'earnest_money' => $userinfo['earnest_money'] + $info['reward_money'], 'old_earnest_money' => $userinfo['earnest_money'], 'change_time' => time(), 'change_desc' => $remark, 'change_type' => 4
                    ];
                    if (!$AccountLogModel->insert($save_data)) {
                        Db::rollback();
                        return $this->error('操作失败');
                    }
                }
                break;
            case 1: // 上级未收款
                if ($info['to_uid'] != $user_id) {
                    Db::rollback(); // 回滚事务
                    return $this->error('无权操作');
                }
                break;
            default :
                Db::rollback(); // 回滚事务
                return $this->error('操作状态错误');
        }
        $res = $RewardLog->where('id', $id)->update(['status' => $status]);
        if ($res < 1) {
            Db::rollback();  // 回滚事务
            return $this->error('操作失败');
        }

        Db::commit();//提交事务
        return $this->success('操作成功');
    }

    /*------------------------------------------------------ */
    //-- 获取电子合同
    /*------------------------------------------------------ */
    public function readcontract()
    {
        $user_id = input('user_id', 0, 'trim');
        $proxyuserModel = new ProxyUsersModel();
        $userinfo = $proxyuserModel->where('user_id', $user_id)->find();
        if ($userinfo['contract'] != "" && $userinfo['contract_time'] > strtotime('-1 year')) {
            return $this->success('获取成功', ['contract' => $userinfo['contract'], 'contract_time' => date("Y-m-d H:i:s", $userinfo['contract_time'])]);
        } else {
            return $this->error('请签约');
        }
    }

    /*------------------------------------------------------ */
    //-- 电子合同签约
    /*------------------------------------------------------ */
    public function writecontract()
    {
        $user_id = $this->userInfo['user_id'];
        $contract = input('contract', '', 'trim');
        if (empty($contract)) {
            return $this->error('缺少参数');
        }
        $proxyuserModel = new ProxyUsersModel();
        $userinfo = $proxyuserModel->where('user_id', $user_id)->update(['contract' => $contract, 'contract_time' => time()]);
        if ($userinfo) {
            return $this->success('签约成功');
        } else {
            return $this->error('签约失败');
        }
    }
}